<template>
  <div class="container">
    <el-form :model="formAdd" ref="formAdd" :rules="formRules">
      <el-form-item label="所属学科" size="small" prop="subjectID">
        <!-- 添加 -->
        <el-select
          v-model="formAdd.subjectID"
          placeholder="请选择"
          style="width: 80%"
        >
          <el-option
            v-for="item in tableData"
            :key="item.id"
            :label="item.subjectName"
            :value="item.subjectID"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录名称" prop="tagName">
        <el-input
          v-model="formAdd.tagName"
          style="width: 80%"
          placeholder="请选择目录名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="addSubmit">确认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/tags.js'
export default {
  props: {
    tableData: {
      type: Array
    },
    isEdit: {
      type: Boolean
    },
    row: {
      type: Object
    }
  },
  data () {
    return {
      formAdd: {
        subjectID: '',
        tagName: '',
        id: this.row.id
      },

      formRules: {
        subjectID: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        tagName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {},
  watch: {
    isEdit: {
      handler (newVal) {
        if (newVal) {
          this.formAdd = JSON.parse(JSON.stringify(this.row))
        }
      },
      immediate: true // 初次进入,立即监听
    }
  },
  methods: {
    cancel () {
      //  关闭对话框
      this.$emit('update:dialogAddVisible', false)
      // 清空表单
      this.formAdd = {
        subjectID: '',
        tagName: ''
      }
    },
    addSubmit () {
      this.$refs.formAdd.validate(async (valid) => {
        if (valid) {
          // isEdit为false的时候,为新增
          if (!this.isEdit) {
            const res = await add(this.formAdd)
            // console.log(res, 8888)
            if (res.status === 200) {
              //  关闭对话框
              this.$emit('update:dialogAddVisible', false)
              // 清空表单
              this.formAdd = {
                subjectID: '',
                tagName: ''
              }
              // 刷新
              this.$emit('success')
            }
          } else {
            // isEdit为true的时候,为修改
            const res = await update(this.formAdd)
            console.log(res, 66666)
            //  关闭对话框
            this.$emit('update:dialogAddVisible', false)
            // 清空表单
            this.formAdd = {
              subjectID: '',
              tagName: ''
            }
            // 刷新
            this.$emit('success')
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="less"></style>
